const express = require('express')
const router = express.Router()
const connection = require('../db/sql')
const jwt = require('jsonwebtoken')
// 引入支付宝配置文件
const alipaySdk = require('../db/alipay')
const AlipayFormData = require('alipay-sdk/lib/form').default

const axios = require('axios')
/**
 * 生成一个订单
 */
router.post('/addOrder', (req, res) => {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  let goodsArr = req.body.arr
  // 生成订单号 order_id，规则：时间戳 + 6位随机数
  function setTimeDateFmt(s) {
    return s < 10 ? '0' + s : s
  }
  function randomNumber() {
    const now = new Date();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();
    month = setTimeDateFmt(month);
    day = setTimeDateFmt(day);
    hour = setTimeDateFmt(hour);
    minutes = setTimeDateFmt(minutes);
    seconds = setTimeDateFmt(seconds);
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    return orderCode;
  }
  /**
   * 未支付：1
   * 待支付：2
   * 支付成功：3
   * 支付失败：4 | 0
   */
  // 商品列表名称
  const goodsName = []
  // 订单商品总金额
  let goodsPrice = 0
  // 订单商品总数量
  let goodsNum = 0
  // 订单号
  let orderId = randomNumber()
  goodsArr.forEach(v => {
    goodsName.push(v.goods_name);
    goodsPrice += v.goods_price * v.goods_num;
    goodsNum += parseInt(v.goods_num);
  })
  //查询当前用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    connection.query(`insert into store_order (order_id,goods_name,goods_price,goods_num,order_status,uId) values ('${orderId}','${goodsName}','${goodsPrice}','${goodsNum}','1',${uId})`, function () {

      connection.query(`select * from store_order where uId = ${uId} and order_id='${orderId}'`, function (err, result) {
        res.send({
          data: {
            success: true,
            code: 200,
            data: result
          }
        })
      })
    })
  })
})

/**
 * 查询一个订单
 */
router.post('/selectOrder', (req, res) => {
  //接收前端给后端的订单号
  let orderId = req.body.orderId;
  connection.query(`select * from store_order where order_id='${orderId}'`, function (err, result) {
    res.send({
      data: {
        success: true,
        code: 200,
        data: result
      }
    })
  })
})

/**
 * 发起支付
 */
router.post('/payment', (req, res) => {
  //订单号
  let orderId = req.body.orderId;
  //商品总价
  let price = req.body.price;
  //购买商品的名称
  let name = req.body.name;
  // 开始对接支付宝API
  const formData = new AlipayFormData();
  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  formData.setMethod('get');
  //支付时信息
  formData.addField('bizContent', {
    outTradeNo: orderId,//订单号
    productCode: 'FAST_INSTANT_TRADE_PAY',//写死的
    totalAmount: price,//价格
    subject: name,//商品名称
  });
  //支付成功或者失败跳转的链接
  formData.addField('returnUrl', 'http://localhost:8080/payment');
  //返回promise
  const result = alipaySdk.exec(
    'alipay.trade.page.pay',
    {},
    { formData: formData },
  );
  //对接支付宝成功，支付宝方返回的数据
  result.then(resp => {
    res.send({
      data: {
        code: 200,
        success: true,
        msg: '支付中',
        paymentUrl: resp
      }
    })
  })
})

/**
 * 修改订单的状态
 */
router.post('/submitOrder', (req, res) => {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //订单号
  let orderId = req.body.orderId;
  //购物车选中的商品id
  let shopArr = req.body.shopArr;
  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uId = results[0].id;
    connection.query(`select * from store_order where uId = ${uId} and order_id = ${orderId}`, function (err, result) {
      //订单的数据库id
      let id = result[0].id;
      //修改订单状态 1==>2
      connection.query(`update store_order set order_status = replace(order_status,'1','2') where id = ${id}`, function (e, r) {
        //购物车数据删除
        shopArr.forEach(v => {
          connection.query(`delete from goods_cart where id = ${v}`, function () {

          })
        })
        res.send({
          data: {
            code: 200,
            success: true
          }
        })
      })
    })
  })
})


/**
 * 支付状态
 */
router.post('/successPayment', (req, res) => {
  //token
  let token = req.headers.token;
  let tokenObj = jwt.decode(token);
  //订单号
  let out_trade_no = req.body.out_trade_no;
  let trade_no = req.body.trade_no;
  //支付宝配置
  const formData = new AlipayFormData();
  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  formData.setMethod('get');
  //支付时信息
  formData.addField('bizContent', {
    out_trade_no,
    trade_no
  });
  //返回promise
  const result = alipaySdk.exec(
    'alipay.trade.query',
    {},
    { formData: formData },
  );
  // 后端请求支付宝
  result.then(resData => {
    axios({
      method: 'GET',
      url: resData
    }).then(data => {
      let responseCode = data.data.alipay_trade_query_response;
      if (responseCode.code == '10000') {
        switch (responseCode.trade_status) {
          case 'WAIT_BUYER_PAY':
            res.send({
              data: {
                code: 0,
                data: {
                  msg: '支付宝有交易记录，没付款'
                }
              }
            })
            break;

          case 'TRADE_CLOSED':
            res.send({
              data: {
                code: 1,
                data: {
                  msg: '交易关闭'
                }
              }
            })
            break;

          case 'TRADE_FINISHED':
            connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
              //用户id
              let uId = results[0].id;
              connection.query(`select * from store_order where uId = ${uId} and order_id = ${out_trade_no}`, function (err, result) {
                let id = result[0].id;
                //订单的状态修改掉2==》3
                connection.query(`update store_order set order_status = replace(order_status,'2','3') where id = ${id}`, function () {
                  res.send({
                    data: {
                      code: 2,
                      data: {
                        msg: '交易完成'
                      }
                    }
                  })
                })
              })
            })
            break;

          case 'TRADE_SUCCESS':
            connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
              //用户id
              let uId = results[0].id;
              connection.query(`select * from store_order where uId = ${uId} and order_id = ${out_trade_no}`, function (err, result) {
                let id = result[0].id;
                //订单的状态修改掉2==》3
                connection.query(`update store_order set order_status = replace(order_status,'2','3') where id = ${id}`, function () {
                  res.send({
                    data: {
                      code: 2,
                      data: {
                        msg: '交易完成'
                      }
                    }
                  })
                })
              })
            })
            break;
        }
      } else if (responseCode.code == '40004') {
        res.send({
          data: {
            code: 4,
            msg: '交易不存在'
          }
        })
      }
    }).catch(err => {
      res.send({
        data: {
          code: 500,
          msg: '交易失败',
          err
        }
      })
    })
  })
})
module.exports = router